import { useLocation as useRemixLocation } from '@remix-run/react';
import { useConfig } from './D8dConfigProvider.tsx';
import { useEffect, useState } from 'react';

interface Location {
  pathname: string;
  search: string;
  hash: string;
  state: unknown;
  key?: string;
}

/**
 * 用于获取当前URL信息的hook
 * 
 * 返回一个包含以下属性的对象：
 * - pathname: URL路径部分
 * - search: 查询字符串
 * - hash: URL哈希部分
 * - state: 位置状态对象
 * - key: 位置的唯一标识符（可选）
 */
export const useLocation = (): Location => {
  const { useSpaRouter } = useConfig();
  const remixLocation = useRemixLocation();
  
  // 在SPA模式下，自定义实现location
  const [spaLocation, setSpaLocation] = useState<Location>({
    pathname: window.location.pathname,
    search: window.location.search,
    hash: window.location.hash,
    state: history.state,
  });
  
  // 监听URL变化
  useEffect(() => {
    if (!useSpaRouter) {
      return;
    }
    
    const updateLocation = () => {
      setSpaLocation({
        pathname: window.location.pathname,
        search: window.location.search,
        hash: window.location.hash,
        state: history.state,
      });
    };
    
    // 首次进入页面也需要更新一次
    updateLocation();
    
    // 监听popstate事件（浏览器前进后退按钮触发）
    window.addEventListener('popstate', updateLocation);
    
    // 监听自定义的路由变化事件
    window.addEventListener('popstate', updateLocation);
    
    return () => {
      window.removeEventListener('popstate', updateLocation);
      window.removeEventListener('popstate', updateLocation);
    };
  }, [useSpaRouter]);
  
  return useSpaRouter ? spaLocation : remixLocation;
}; 